<template>
  <div class="manage-users">
    <div class="page-header">
      <h1>用户管理</h1>
    </div>

    <!-- 搜索和过滤 -->
    <div class="search-bar">
      <el-input
        v-model="searchQuery"
        placeholder="搜索用户名或手机号"
        prefix-icon="el-icon-search"
        clearable
        @clear="handleSearch"
      ></el-input>
      <el-select v-model="roleFilter" placeholder="角色筛选" clearable @change="handleRoleFilter">
        <el-option label="全部角色" value="all"></el-option>
        <el-option label="普通用户" value="user"></el-option>
        <el-option label="管理员" value="admin"></el-option>
      </el-select>
      <el-button type="primary" @click="handleSearch">搜索</el-button>
    </div>

    <!-- 用户列表 -->
    <el-table
      v-loading="loading"
      :data="displayedUsers"
      border
      style="width: 100%"
      class="mt-4"
    >
      <el-table-column prop="username" label="用户名" width="200"/>
      <el-table-column prop="_id" label="用户ID" width="260"/>
      <el-table-column prop="avatar" label="头像" width="100">
        <template #default="scope">
          <img 
          v-if="scope.row.avatar"
          :src="`http://localhost:5000/uploads/${scope.row.avatar}`" 
          alt="头像"
          style="width: 40px; height: 40px; border-radius: 50%;"
          >
          <img v-else src="@/assets/touxiang.png" alt="默认头像" style="width: 40px; height: 40px; border-radius: 50%;">
        </template>
      </el-table-column>
      <el-table-column prop="phone" label="手机号" width="150"/>
      <el-table-column prop="schoolName" label="所属学校" width="180">
        <template #default="scope">
          {{ scope.row.schoolName || '未分配' }}
        </template>
      </el-table-column>
      <el-table-column prop="clubs" label="加入的社团" width="180">
        <template #default="scope">
          {{ scope.row.clubs.length || '未加入任何社团' }}
        </template>
      </el-table-column>
      <el-table-column label="角色" width="100">
        <template #default="scope">
          <el-tag v-if="scope.row.roles && scope.row.roles.includes('systemAdmin')" type="danger">管理员</el-tag>
          <el-tag v-else type="info">普通用户</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="注册时间" width="200">
        <template #default="scope">
          {{ scope.row.registration_time ? new Date(scope.row.registration_time).toLocaleString() : 'N/A' }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="240" fixed="right">
        <template #default="scope">
          <el-button
            type="info"
            size="small"
            @click="viewDetails(scope.row)"
            style="margin-right: 5px;"
          >
            详情
          </el-button>
          <el-button
            type="primary"
            size="small"
            @click="changeRole(scope.row)"
            :disabled="isCurrentUser(scope.row)"
            style="margin-right: 5px;"
          >
            角色
          </el-button>
          <el-button
            type="danger"
            size="small"
            @click="confirmDelete(scope.row)"
            :disabled="isCurrentUser(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页控件 -->
    <div class="pagination-container">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalItems"
        :page-size="pageSize"
        :current-page="currentPage"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      />
    </div>

    <!-- 更改角色对话框 -->
    <el-dialog
      title="更改用户角色"
      v-model="roleDialogVisible"
      width="30%"
    >
      <div>
        <p>用户: <strong>{{ selectedUser?.username }}</strong></p>
        <p>当前角色: <strong>{{ getRoleDisplay(selectedUser?.roles) }}</strong></p>
        <el-divider></el-divider>
        <el-radio-group v-model="newRole">
          <el-radio label="user">普通用户</el-radio>
          <el-radio label="systemAdmin">管理员</el-radio>
        </el-radio-group>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="roleDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmRoleChange">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 删除确认对话框 -->
    <el-dialog
      title="确认删除"
      v-model="deleteDialogVisible"
      width="30%"
    >
      <p>确定要删除用户 "{{ selectedUser?.username }}" 吗？此操作不可撤销。</p>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="deleteUser">删除</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 新增：用户详情对话框 -->
    <el-dialog
      title="用户详情"
      v-model="detailsDialogVisible"
      width="600px"
      top="5vh"
    >
      <div v-if="loadingDetails">加载中...</div>
      <div v-else-if="selectedUserDetails" class="user-details">
         <el-descriptions :column="2" border>
             <el-descriptions-item label="用户名">{{ selectedUserDetails.username }}</el-descriptions-item>
             <el-descriptions-item label="手机号">{{ selectedUserDetails.phone }}</el-descriptions-item>
             <el-descriptions-item label="用户ID">{{ selectedUserDetails._id }}</el-descriptions-item>
              <el-descriptions-item label="角色">
                  <el-tag v-for="role in selectedUserDetails.roles" :key="role" :type="role === 'systemAdmin' ? 'danger' : 'info'" style="margin-right: 5px;">
                      {{ role === 'systemAdmin' ? '管理员' : '普通用户' }}
                  </el-tag>
              </el-descriptions-item>
             <el-descriptions-item label="性别">{{ selectedUserDetails.gender || '未设置' }}</el-descriptions-item>
             <el-descriptions-item label="生日">
                 {{ selectedUserDetails.birthday ? new Date(selectedUserDetails.birthday).toLocaleDateString() : '未设置' }}
             </el-descriptions-item>
             <el-descriptions-item label="所属学校" :span="2">
                 {{ selectedUserDetails.school?.name || '未分配' }}
             </el-descriptions-item>
              <el-descriptions-item label="加入的社团" :span="2">
                 <div v-if="selectedUserDetails.clubs && selectedUserDetails.clubs.length > 0">
                     <el-tag v-for="club in selectedUserDetails.clubs" :key="club._id" type="success" style="margin-right: 5px; margin-bottom: 5px;">
                         {{ club.clubname }}
                     </el-tag>
                 </div>
                  <span v-else>未加入任何社团</span>
              </el-descriptions-item>
             <el-descriptions-item label="个性签名" :span="2">{{ selectedUserDetails.signature || '无' }}</el-descriptions-item>
             <el-descriptions-item label="注册时间" :span="2">
                 {{ selectedUserDetails.registration_time ? new Date(selectedUserDetails.registration_time).toLocaleString() : 'N/A' }}
             </el-descriptions-item>
              <el-descriptions-item label="头像" :span="2">
                   <el-avatar v-if="selectedUserDetails.avatar" :size="60" :src="`http://localhost:5000/uploads/${selectedUserDetails.avatar}`" />
                   <span v-else>未设置</span>
              </el-descriptions-item>
         </el-descriptions>
      </div>
       <div v-else>无法加载用户详情。</div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailsDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';
import { ref, computed, onMounted, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useStore } from '@/stores/userStore';
// import defaultAvatar from '@/assets/touxiang.png';

export default {
  name: 'ManageUsers',
  setup() {
    const userStore = useStore();
    const currentUser = computed(() => userStore.user);

    // 状态变量
    const allUsers = ref([]);
    const loading = ref(false);
    const searchQuery = ref('');
    const roleFilter = ref('all');
    const currentPage = ref(1);
    const pageSize = ref(10);
    const totalItems = ref(0);

    // 对话框控制
    const roleDialogVisible = ref(false);
    const selectedUser = ref(null);
    const newRole = ref('');
    const deleteDialogVisible = ref(false);

    // 新增：详情对话框状态
    const detailsDialogVisible = ref(false);
    const selectedUserDetails = ref(null);
    const loadingDetails = ref(false);

    // 直接从服务器获取用户数据
    const displayedUsers = computed(() => {
      return allUsers.value;
    });

    // 辅助函数 - 检查是否是当前登录用户
    const isCurrentUser = (user) => {
      return currentUser.value && user && currentUser.value.id === user._id;
    };

    // 辅助函数 - 获取角色显示文本
    const getRoleDisplay = (roles) => {
      if (!roles) return '普通用户';
      return roles.includes('systemAdmin') ? '管理员' : '普通用户';
    };

    // 加载用户数据
    const loadUsers = async () => {
      try {
        loading.value = true
        const token = localStorage.getItem('token');
        if (!token) {
          ElMessage.error('请先登录');
          loading.value = false;
          return;
        }

        // API url with pagination parameters
        const apiUrl = `http://localhost:5000/users?page=${currentPage.value}&limit=${pageSize.value}${
          searchQuery.value ? `&search=${encodeURIComponent(searchQuery.value)}` : ''
        }${roleFilter.value !== 'all' ? `&role=${roleFilter.value}` : ''}`;

        const response = await axios.get(apiUrl, {
           headers: { Authorization: `Bearer ${token}` }
        });

        allUsers.value = response.data.users;
        totalItems.value = response.data.total;

        loading.value = false;
      } catch (error) {
        console.error('加载用户数据失败', error);
        if (error.response && error.response.status === 403) {
             ElMessage.error('权限不足，无法访问用户管理');
        } else if (error.response && error.response.status === 401) {
             ElMessage.error('登录状态无效，请重新登录');
             userStore.logout();
        }
         else {
            ElMessage.error('加载用户数据失败');
        }
        allUsers.value = [];
        totalItems.value = 0;
        loading.value = false;
      }
    };

    // 处理页码变化
    const handleCurrentChange = (val) => {
      currentPage.value = val;
      loadUsers();
    };

    // 处理每页条数变化
    const handleSizeChange = (val) => {
      pageSize.value = val;
      currentPage.value = 1;
      loadUsers();
    };

    // 处理搜索
    const handleSearch = () => {
      currentPage.value = 1;
      loadUsers();
    };

    // 处理角色筛选
    const handleRoleFilter = () => {
      currentPage.value = 1;
      loadUsers();
    };

    // 修改用户角色
    const changeRole = (user) => {
      selectedUser.value = user;
      newRole.value = user.roles.includes('systemAdmin') ? 'systemAdmin' : 'user';
      roleDialogVisible.value = true;
    };

    // 确认修改角色
    const confirmRoleChange = async () => {
      if (!selectedUser.value) return;

      const token = localStorage.getItem('token');
      if (!token) {
         ElMessage.error('请先登录');
         return;
      }

      if (isCurrentUser(selectedUser.value)) {
         ElMessage.warning('不能修改自己的角色');
         roleDialogVisible.value = false;
         return;
       }

      loading.value = true;
      try {
        const apiUrl = `http://localhost:5000/users/${selectedUser.value._id}/role`;
        await axios.put(apiUrl, {
           roles: [newRole.value]
        }, {
           headers: { Authorization: `Bearer ${token}` }
        });

        ElMessage.success('角色修改成功');
        roleDialogVisible.value = false;
        await loadUsers();
      } catch (error) {
        console.error('角色修改失败:', error);
        ElMessage.error(error.response?.data?.message || '角色修改失败');
      } finally {
        loading.value = false;
      }
    };

    // 确认删除用户
    const confirmDelete = (user) => {
       if (isCurrentUser(user)) {
         ElMessage.warning('不能删除自己');
         return;
       }
      selectedUser.value = user;
      deleteDialogVisible.value = true;
    };

    // 删除用户
    const deleteUser = async () => {
      if (!selectedUser.value) return;

      if (isCurrentUser(selectedUser.value)) {
         ElMessage.warning('不能删除自己');
         deleteDialogVisible.value = false;
         return;
       }

      const token = localStorage.getItem('token');
        if (!token) {
            ElMessage.error('请先登录');
            return;
        }

      loading.value = true;
      try {
        const apiUrl = `http://localhost:5000/users/${selectedUser.value._id}`;
        await axios.delete(apiUrl, {
             headers: { Authorization: `Bearer ${token}` }
        });

        ElMessage.success('用户删除成功');
        deleteDialogVisible.value = false;
         const remainingItems = totalItems.value - 1;
         const currentPageSize = pageSize.value > 0 ? pageSize.value : 10;
         const totalPages = Math.ceil(remainingItems / currentPageSize);
         if (currentPage.value > totalPages && totalPages > 0) {
           currentPage.value = totalPages;
         } else if (remainingItems === 0) {
            currentPage.value = 1;
         }
        await loadUsers();
      } catch (error) {
        console.error('用户删除失败:', error);
        ElMessage.error(error.response?.data?.message || '用户删除失败');
      } finally {
        loading.value = false;
      }
    };

    // 新增：查看详情方法
    const viewDetails = async (user) => {
        selectedUser.value = user;
        selectedUserDetails.value = null;
        detailsDialogVisible.value = true;
        loadingDetails.value = true;

        const token = localStorage.getItem('token');
        if (!token) {
            ElMessage.error('请先登录');
            loadingDetails.value = false;
            detailsDialogVisible.value = false;
            return;
        }

        try {
            const apiUrl = `http://localhost:5000/users/${user._id}/details`;
            const response = await axios.get(apiUrl, {
                headers: { Authorization: `Bearer ${token}` }
            });
            selectedUserDetails.value = response.data;
        } catch (error) {
            console.error('获取用户详情失败:', error);
            ElMessage.error(error.response?.data?.message || '获取用户详情失败');
            detailsDialogVisible.value = false;
        } finally {
            loadingDetails.value = false;
        }
    };

    // 监听搜索查询的变化，并在变化时重新加载数据
    watch(searchQuery, (newValue, oldValue) => {
        if (newValue !== oldValue) {
            currentPage.value = 1;
            loadUsers();
        }
    });

    // 监听角色筛选器的变化
    watch(roleFilter, (newValue, oldValue) => {
         if (newValue !== oldValue) {
            currentPage.value = 1;
            loadUsers();
         }
    });

    // 组件挂载时加载用户
    onMounted(() => {
      if (!currentUser.value && localStorage.getItem('token')) {
         userStore.fetchUserInfo().then(() => {
             loadUsers();
         });
       } else {
         loadUsers();
       }
    });

    return {
      // 状态
      allUsers,
      loading,
      searchQuery,
      roleFilter,
      currentPage,
      pageSize,
      totalItems,
      displayedUsers,
      roleDialogVisible,
      selectedUser,
      newRole,
      deleteDialogVisible,
      currentUser,
      detailsDialogVisible,
      selectedUserDetails,
      loadingDetails,

      // 方法
      loadUsers,
      handleCurrentChange,
      handleSizeChange,
      handleSearch,
      handleRoleFilter,
      changeRole,
      confirmRoleChange,
      confirmDelete,
      deleteUser,
      getRoleDisplay,
      isCurrentUser,
      viewDetails,
    };
  }
};
</script>

<style scoped>
.manage-users {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0;
  font-size: 24px;
  color: #303133;
}

.search-bar {
  display: flex;
  margin-bottom: 20px;
  gap: 10px;
}

.search-bar .el-input {
  width: 300px;
}

.search-bar .el-select {
  width: 150px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.mt-4 {
  margin-top: 1.5rem;
}

.el-table {
  background-color: #fff;
}

.el-dialog__body {
  padding: 20px;
}

.el-dialog__footer {
  padding: 10px 20px;
  text-align: right;
}

.el-button.is-disabled {
    cursor: not-allowed;
}

/* 详情对话框样式 */
.user-details .el-descriptions {
    margin-top: 10px;
}
.user-details .el-tag {
    margin-bottom: 5px;
}
</style>
